//
//  CRCommentViewController.m
//  CRChatRoom
//
//  Created by CuiFengshuai on 15/11/28.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRCommentViewController.h"
#import "AFHTTPSessionManager.h"
#import "CRCommentCell.h"
#import "CRCommentHeader.h"
#import "CRTopic.h"
#import "CRTopicCell.h"
#import "MJRefresh.h"
#import "CRComment.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
@interface CRCommentViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;


/** 保存最热评论 */
@property (nonatomic, strong) id top_cmt;

/** 管理者 */
@property (nonatomic, weak) AFHTTPSessionManager *manager;

/** 最热评论数据 */
@property (nonatomic, strong) NSArray *hotComments;
/** 最新评论数据 */
@property (nonatomic, strong) NSMutableArray *lastestComments;
@end

@implementation CRCommentViewController

static NSString * const CRCommentCellId = @"comment";
static NSString * const CRCommentHeaderId = @"comment-header";
#pragma mark >>>> 懒加载

- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
#pragma mark >>>> 系统方法
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 自定义控件初始化
    [self setupSubViews];

    // 初始化数据模型
    [self initData];
}

#pragma mark >>>> 初始化方法
/**
 *  自定义控件初始化
 */
- (void)setupSubViews {
    [self setupNav];
    
    [self setupTableView];
    
    [self setupHeaderView];
}

/**
 *  初始化数据模型
 */
- (void)initData {
    [self setupRefresh];
}
#pragma mark >>>> 初始化方法实现

- (void)setupRefresh {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewComments)];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreComments)];
}

/**
 *  设置导航栏
 */
- (void)setupNav {
    self.title = @"评论";
    // 设置导航栏右边的按钮
    
    UIButton *button = [self itemWithTarget:self action:@selector(didClickRightBarButton:) image:[UIImage imageNamed:@"comment_nav_item_share_icon"] highImage:[UIImage imageNamed:@"comment_nav_item_share_icon_click"]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    UIButton *backBtn = [self itemWithTarget:self action:@selector(didClickLeftBarButton:) image:[UIImage imageNamed:@"backNormal"] highImage:[UIImage imageNamed:@"baclhigh"]];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    
    
    // 接收键盘frame改变的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}

- (void)setupTableView {
    self.tableView.backgroundColor = CRGlobalBg;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 注册cell 
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CRCommentCell class]) bundle:nil] forCellReuseIdentifier:CRCommentCellId];
    // 注册headerView
    [self.tableView registerClass:[CRCommentHeader class] forHeaderFooterViewReuseIdentifier:CRCommentHeaderId];
    
    //  设置估计行高
    self.tableView.estimatedRowHeight = 100;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}


- (void)setupHeaderView {
    // 去除最热评论
    if (self.topic.top_cmt) {
        self.top_cmt = self.topic.top_cmt;
        self.topic.top_cmt = nil;
        self.topic.cellHeight = 0;
    }
    // headerView
    UIView *header = [[UIView alloc] init];
    
    // header内部的cell
    CRTopicCell *cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([CRTopicCell class]) owner:nil options:nil] lastObject];
    cell.topic = self.topic;
    cell.frame = CGRectMake(0, 0, CRScreenW, self.topic.cellHeight);
    [header addSubview:cell];
    
    // header的高度
    header.height = cell.height + CRMargin;
    
    self.tableView.tableHeaderView = header;
}


#pragma mark >>>> 事件监听方法

- (void)didClickRightBarButton:(UIButton *)button {
    [UIView animateWithDuration:1.5 animations:^{
        [MBProgressHUD showMessage:@"未完待续....."];
    } completion:^(BOOL finished) {
        [MBProgressHUD hideHUD];
    }];
}

- (void)didClickLeftBarButton:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  下拉刷新
 */
- (void)loadNewComments {
    // 取消之前的所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"dataList";
    params[@"c"] = @"comment";
    params[@"data_id"] = self.topic.ID;
    params[@"hot"] = @1;
    
    // 发送请求
    CRWeakSelf;
    [self.manager GET:CRBaseURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        // 结束刷新
        if ([responseObject isKindOfClass:[NSArray class]]) {
            [weakSelf.tableView.mj_header endRefreshing];
            return ;
        }
        // 数据处理
        
        weakSelf.hotComments = [CRComment mj_objectArrayWithKeyValuesArray:responseObject[@"hot"]];
        weakSelf.lastestComments = [CRComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        // 刷新表格
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
        // 所有数据加载完毕
        if (weakSelf.lastestComments.count >= [responseObject[@"total"] intValue]) {
#warning  ------>当评论数 铺不满屏幕 下面footer 不消失
            weakSelf.tableView.mj_footer.hidden = YES;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

/**
 *  上拉加载
 */
- (void)loadMoreComments {
    // 取消之前的所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"dataList";
    params[@"c"] = @"comment";
    params[@"data_id"] = self.topic.ID;
    params[@"lastcid"] = [[self.lastestComments lastObject] ID];
    
    // 发送请求
    CRWeakSelf;
    [self.manager GET:CRBaseURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            weakSelf.tableView.mj_footer.hidden = YES;
            return ;
        }
        
        // 数据处理
        NSArray *newComments = [CRComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [weakSelf.lastestComments addObjectsFromArray:newComments];
        
        // 刷新表格
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
        });
        
        // 结束刷新
        if (weakSelf.lastestComments.count >= [responseObject[@"total"] intValue]) { // 所以数据加载完毕
            weakSelf.tableView.mj_footer.hidden = YES;
        } else {
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 结束刷新
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
    
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    
    CGFloat keyboardY = [notification.userInfo [UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    self.bottomSpace.constant = CRScreenH - keyboardY;
    
    // 动画时间
    double duration = [notification.userInfo [UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)dealloc {
    [self.manager invalidateSessionCancelingTasks:YES];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    //
    if (self.top_cmt) {
        self.topic.top_cmt = self.top_cmt;
        self.topic.cellHeight = 0;
    }
}
#pragma mark >>>> 实现代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.hotComments.count)  return 2;
    if (self.lastestComments.count) return 1;
    return 0;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0 && self.hotComments.count) return self.hotComments.count;
    
    return self.lastestComments.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CRComment *comment = nil;

    if (indexPath.section == 0 && self.hotComments.count) {
        comment = self.hotComments[indexPath.row];
    } else {
        comment = self.lastestComments[indexPath.row];
    }
    CRCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:CRCommentCellId forIndexPath:indexPath];
    
    cell.comment = comment;
    
    return cell;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CRCommentHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CRCommentHeaderId];
    if (section == 0 && self.hotComments.count) {
        header.text = @"最热评论";
    } else {
        header.text = @"最新评论";
    }
    return header;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 自定义菜单选项
    UIMenuController *menu = [UIMenuController sharedMenuController];
    // 如果之前已经设置过了 就直接返回 不显示
    if (menu.menuItems) {
        menu.menuItems = nil;
        return;
    }
    
    [self becomeFirstResponder];
    // cell
    CRCommentCell *cell = (CRCommentCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    // 设置显示范围
    [menu setTargetRect:CGRectMake(0, cell.height * 0.5, cell.width, 1) inView:cell];
    // 添加自定义菜单
    menu.menuItems = @[
                       [[UIMenuItem alloc] initWithTitle:@"顶" action:@selector(ding)],
                       [[UIMenuItem alloc] initWithTitle:@"回复" action:@selector(reply)],
                       [[UIMenuItem alloc] initWithTitle:@"举报" action:@selector(warning)]
                       ];
    [menu setMenuVisible:YES animated:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    // 当开始滑动时 所有界面停止编辑
    [self.view endEditing:YES];
}

#pragma mark >>>> 菜单监听方法
- (void)ding
{
    NSLog(@"%s", __func__);
}

- (void)reply
{
    NSLog(@"%s", __func__);
}

- (void)warning
{
    NSLog(@"%s", __func__);
}
#pragma mark >>>> 其他方法
- (UIButton *)itemWithTarget:(id)target action:(SEL)action image:(UIImage *)image highImage:(UIImage *)highImage {
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 30, 30);
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:highImage forState:UIControlStateHighlighted];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}


- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)resignFirstResponder {
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    menu.menuItems = nil;
    return [super resignFirstResponder];
}


@end
